package com.ruoyi.combat.service.camera.impl;

import java.io.*;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.*;

import cn.hutool.core.io.FileUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.ruoyi.combat.domain.camera.CombatCameraGeo;
import com.ruoyi.combat.domain.camera.CombatCameraGeoResult;
import com.ruoyi.combat.domain.camera.CombatCameraInfo;
import com.ruoyi.combat.mapper.camera.CombatCameraGeoMapper;
import com.ruoyi.combat.mapper.camera.CombatCameraGeoResultMapper;
import com.ruoyi.combat.mapper.camera.CombatCameraInfoMapper;
import com.ruoyi.combat.service.camera.ICombatCameraGeoService;
import com.ruoyi.combat.util.MethodUseUtils;
import com.ruoyi.file.service.ISysFileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 摄像头定位信息Service业务层处理
 *
 * @author ruoyi
 * @date 2025-01-08
 */
@Service
public class CombatCameraGeoServiceImpl implements ICombatCameraGeoService {
    @Autowired
    private CombatCameraInfoMapper combatCameraInfoMapper;
    @Autowired
    private CombatCameraGeoMapper combatCameraGeoMapper;

    @Autowired
    private CombatCameraGeoResultMapper combatCameraGeoResultMapper;

    @Autowired
    private MethodUseUtils methodUseUtils;

    @Autowired
    private ISysFileService fileService;

    /**
     * 查询摄像头定位信息
     *
     * @param id 摄像头定位信息主键
     * @return 摄像头定位信息
     */
    @Override
    public CombatCameraGeo selectCombatCameraGeoById(Long id) {
        return combatCameraGeoMapper.selectCombatCameraGeoById(id);
    }

    /**
     * 查询摄像头定位信息列表
     *
     * @param combatCameraGeo 摄像头定位信息
     * @return 摄像头定位信息
     */
    @Override
    public List<CombatCameraGeo> selectCombatCameraGeoList(CombatCameraGeo combatCameraGeo) {
        return combatCameraGeoMapper.selectCombatCameraGeoList(combatCameraGeo);
    }

    /**
     * 新增摄像头定位信息
     *
     * @param combatCameraGeo 摄像头定位信息
     * @return 结果
     */
    @Override
    public int insertCombatCameraGeo(CombatCameraGeo combatCameraGeo) {
        Long cameraId = combatCameraGeo.getCameraId();
        if(cameraId!=null){
            CombatCameraInfo combatCameraInfo = combatCameraInfoMapper.selectCombatCameraInfoById(cameraId);
            String name = combatCameraInfo.getCameraIp() + ":" + combatCameraInfo.getCameraPort();
            combatCameraGeo.setCameraName(name);
            combatCameraGeo.setImgName(name);
        }else{
            combatCameraGeo.setCameraName("-");
            combatCameraGeo.setImgName(combatCameraGeo.getImgGeo()+"图像");
        }

        combatCameraGeo.setStatus("0");
        int i = combatCameraGeoMapper.insertCombatCameraGeo(combatCameraGeo);
        callImagePositioning(combatCameraGeo);
        return i;
    }

    /**
     * {
     * "image": "/9j/4AAQSkZJRB.....+4F7nbDMf/9k=",
     * "city": "上海",
     * "topk": 1  默认20
     * }
     * @param combatCameraGeo
     */

    public void callImagePositioning(CombatCameraGeo combatCameraGeo) {
        // 获取摄像头id
        Long cameraId = combatCameraGeo.getCameraId();
        Long id = combatCameraGeo.getId();
        // 获取图片城市信息
        String imgGeo = combatCameraGeo.getImgGeo();
        // 摄像头定位返回个数
        Long cameraGeoNum = combatCameraGeo.getImgGeoNum();
        String imgUrl = combatCameraGeo.getImgUrl();
        byte[] bytes = fileService.download(imgUrl);
        String imgBase64 = Base64.getEncoder().encodeToString(bytes);
        String methodId = combatCameraGeo.getMethodId();
        String[] split = methodId.split(",");
        String s = split[0];
        Map<String, Object> data = new HashMap();
//        imgGeo = "上海";
        data.put("image", imgBase64);
        data.put("city", imgGeo);
        data.put("topk", cameraGeoNum);
        String jsonStr = JSONUtil.toJsonStr(data);
        Map<String, Object> stringObjectMap = methodUseUtils.methodUseLogs(Long.parseLong(s), jsonStr);
        if(stringObjectMap.get("gps")!=null) {
//            List<String> idx = (List<String>) stringObjectMap.get("idx");
            List<String> location = (List<String>) stringObjectMap.get("location");
            List<List<String>> gps = (List<List<String>>) stringObjectMap.get("gps");

            for (int i = 0; i < gps.size(); i++) {
                CombatCameraGeoResult result = new CombatCameraGeoResult();
                result.setGeoId(id);
                result.setMethodId(Long.parseLong(s));
                result.setMethodName(s);
                result.setAddress(location.get(i));
                String lon = String.valueOf(gps.get(i).get(0));
                String lat = String.valueOf(gps.get(i).get(1));
                result.setLon(lon);
                result.setLat(lat);
                result.setCreateTime(new Date());
                combatCameraGeoResultMapper.insertCombatCameraGeoResult(result);
            }
        }
        combatCameraGeo.setStatus("1");
        combatCameraGeoMapper.updateCombatCameraGeo(combatCameraGeo);
    }

    /**
     * 下载网络图片
     * @param urlList  网络路径
     */
    public static byte[] downloadPicture(String urlList) {
        URL url = null;
        try {
            url = new URL(urlList);
            DataInputStream dataInputStream = new DataInputStream(url.openStream());

            ByteArrayOutputStream output = new ByteArrayOutputStream();

            byte[] buffer = new byte[1024];
            int length;

            while ((length = dataInputStream.read(buffer)) > 0) {
                output.write(buffer, 0, length);
            }
            byte[] byteArray = output.toByteArray();
            dataInputStream.close();
            return byteArray;
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }


    public static void main(String[] args) {

        String url = "http://192.168.101.7:9001/api/v1/buckets/combat/objects?prefix=Lw==";

        HttpRequest get = HttpUtil.createGet(url);
        get.header("cookie", "token=AFHMZmkJYLcIyVOS10qjdu13HvBsoXjPie7E4JtRLd0ldfwvhMeXlQKEICrolxzfXTL05FUeQs+bgmeJkKFrxbr11RYkjg+eqqZEq25kqOrVmOeMEpVVoQ4eKLxkOhBKgMMAsPpb8glIvWwEEQz8CDrIlcDN21qP/vsr6H+UU1Pjxv2KkZOKgxMq2NGGEO/Ap5Kr3PxKinSnAUaI5bI5ObMsRXBXevZffFTADBkcBtvkSXDPTpuLIpjSEGX29ShLJAWdLKPiREdZrIuEuwot+equLpaJPdcE8qrSDpWrNUXdVbSay8LUuDhWEfkP0hVTobsob0g0GWHJHmdXgVEyrfSSfNdPV/eTuuTYdeI++UWG7rzCcydcp6+sSFNiueJjYj3COPhPpTZ2rZt0ZQEAsXB081nO6RI7JiENLGh5KJk1xlAJssstSbt3L0Jxt1d0THRJy0DHkN3nWI0J1fScqggBSNaQt7NSVmjOl1N/hg649LK3f08e+qBQkJAWbbRoY+iqr/PZwPcenOBqiV6KYxwXqmz+VcrzVtdkbWjrGignazS8cuzOcQ7n7VWuxEXsYwhm5zRvoPHP8HoReHHmgWnOlQ==");

        HttpResponse execute = get.execute();

        String body = execute.body();
        Map bean = JSONUtil.toBean(body, Map.class);
        String jsonStr = JSONUtil.toJsonStr(bean.get("objects"));

        List<Map> list = JSONUtil.toList(jsonStr, Map.class);

        String ipUrl = "http://192.168.101.7:8888/";
        for (Map map: list){
            String name = String.valueOf(map.get("name"));

            String urlStr = ipUrl +"combat/"+ name;

            File localFile = new File("E:\\combat\\" + name);
            byte[] bytes = downloadPicture(urlStr);
            FileUtil.writeBytes(bytes, localFile);

            System.out.println(name);
        }


        System.out.println(list.size());


        /*String baiduLogoUrl = "http://192.168.101.7:8888/combat/00026dccfd00dd70b01179a7f5e7dfd5.jpg";
        File localFile = new File("E:\\test\\" + "bd_logo1.png");
        byte[] bytes = downloadPicture(baiduLogoUrl);
        FileUtil.writeBytes(bytes, localFile);*/
    }



    /**
     * 修改摄像头定位信息
     *
     * @param combatCameraGeo 摄像头定位信息
     * @return 结果
     */
    @Override
    public int updateCombatCameraGeo(CombatCameraGeo combatCameraGeo) {
        return combatCameraGeoMapper.updateCombatCameraGeo(combatCameraGeo);
    }

    /**
     * 批量删除摄像头定位信息
     *
     * @param ids 需要删除的摄像头定位信息主键
     * @return 结果
     */
    @Override
    public int deleteCombatCameraGeoByIds(Long[] ids) {
        return combatCameraGeoMapper.deleteCombatCameraGeoByIds(ids);
    }

    /**
     * 删除摄像头定位信息信息
     *
     * @param id 摄像头定位信息主键
     * @return 结果
     */
    @Override
    public int deleteCombatCameraGeoById(Long id) {
        return combatCameraGeoMapper.deleteCombatCameraGeoById(id);
    }
}
